﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using CivilleWP7.Civille.Source;
using System.Collections.ObjectModel;
using CivilleWP7.CivilleDataServiceReference;
using System.Data.Services.Client;
using CivilleWP7.Views.Controls;
using SL.Phone.Federation.Utilities;
using System.Windows.Media.Imaging;
using ScottIsAFool.Controls;
using Microsoft.Phone.Notification;
using System.IO.IsolatedStorage;
using System.IO;
using Microsoft.Phone.Shell;

namespace CivilleWP7.Views.Pages
{
    public partial class PanoramaPage : PhoneApplicationPage
    {
        private List<Task> panoramaTasks;
        RequestSecurityTokenResponseStore _rstrStore = App.Current.Resources["rstrStore"] as RequestSecurityTokenResponseStore;
        private string Uri;

        public PanoramaPage()
        {
            InitializeComponent();

            
            this.Loaded += new RoutedEventHandler(PanoramaPage_Loaded);
        }

        private void LoadCurrentUserData()
        {
            if (!_rstrStore.ContainsValidRequestSecurityTokenResponse() || SelectAuthPage.IsTokenExpired(_rstrStore.RequestSecurityTokenResponse.expires))
            {
                NavigationService.Navigate(new Uri("/Views/Pages/SelectAuthPage.xaml", UriKind.Relative));
            }
            else
            {
                CivilleDataServiceConnector.SetGetUserParameters(UserContext.GetCurrentToken());
                CivilleDataServiceConnector.GetUserQuery.BeginExecute((result) =>
                {
                    Dispatcher.BeginInvoke(() =>
                        {
                            DataServiceQuery<CivilleUser> queryEnd = result.AsyncState as DataServiceQuery<CivilleUser>;
                            foreach (CivilleUser user in queryEnd.EndExecute(result))
                            {
                                UserContext.CurrentUser = user;
                                SetIconsColor();
                                GetPanoramaTasks();
                                GetLeaderboardPosition();
                                GetFriends();
                                BuildExploreTiles();
                                Intro.Visibility = System.Windows.Visibility.Collapsed;
                                if (!HasUserSeenIntro())
                                {
                                    Intro.Visibility = System.Windows.Visibility.Visible;
                                }
                            }
                        });
                },
                CivilleDataServiceConnector.GetUserQuery);
            }
        }

        protected void RegisterForPushNotifications()
        {
            /// Holds the push channel that is created or found.
            HttpNotificationChannel pushChannel;

            // The name of our push channel.
            string channelName = "TileSampleChannel";

            // Try to find the push channel.
            pushChannel = HttpNotificationChannel.Find(channelName);

            // If the channel was not found, then create a new connection to the push service.
            if (pushChannel == null)
            {
                pushChannel = new HttpNotificationChannel(channelName);

                // Register for all the events before attempting to open the channel.
                pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
                pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);

                pushChannel.Open();

                // Bind this new channel for Tile events.
                pushChannel.BindToShellTile();
            }
            else
            {
                // The channel was already open, so just register for all the events.
                pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
                pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);

                // Display the URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
                Uri = pushChannel.ChannelUri.ToString();
                RegisterUri(Uri);
                System.Diagnostics.Debug.WriteLine(Uri);
            }
        }

        void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
        {

            Dispatcher.BeginInvoke(() =>
            {
                // Display the new URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
                Uri = e.ChannelUri.ToString();
                RegisterUri(Uri);
                System.Diagnostics.Debug.WriteLine(Uri);
            });
        }

        void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
        {
            // Error handling logic for your particular application would be here.
            Dispatcher.BeginInvoke(() =>
                MessageBox.Show(String.Format("A push notification {0} error occurred.  {1} ({2}) {3}",
                    e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData))
                    );
        }

        private void RegisterUri(string URI)
        {
            CivilleDataServiceConnector.RegisterUriForPushNotificationsQueryParameters(URI);
            CivilleDataServiceConnector.RegisterUriForPushNotificationsQuery.BeginExecute(OnRegisterCompleted, CivilleDataServiceConnector.RegisterUriForPushNotificationsQuery);
        }

        private void OnRegisterCompleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
            {
                try
                {
                    DataServiceQuery<MobileUser> query = result.AsyncState as DataServiceQuery<MobileUser>;
                    List<MobileUser> mobileUsers = query.EndExecute(result).ToList();


                    if (mobileUsers.Count == 0)
                    {
                        MobileUser newMobileUser = new MobileUser();
                        newMobileUser.URI = Uri;
                        CivilleDataServiceConnector.CivilleContext.AddToMobileUsers(newMobileUser);
                        CivilleDataServiceConnector.CivilleContext.BeginSaveChanges(OnSaveChangesCompleted, CivilleDataServiceConnector.CivilleContext);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("We couldn't register you for push notifications. Sorry :)");
                }
            });
        }

        protected void OnSaveChangesCompleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
            {
                CivilleDataServiceConnector.CivilleContext.EndSaveChanges(result);
            });
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
        }

        private static bool hasSeenIntro;

        public static bool HasUserSeenIntro()
        {
            if (hasSeenIntro) return true;

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.FileExists("civillefirst"))
                {
                    // just write a placeholder file one byte long so we know they've landed before
                    using (var stream = store.OpenFile("civillefirst", FileMode.Create))
                    {
                        stream.Write(new byte[] { 1 }, 0, 1);
                    }
                    return false;
                }
                hasSeenIntro = true;
                return true;
            }
        }


        void PanoramaPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                ShellTile firstTile = ShellTile.ActiveTiles.First();
                var newData = new StandardTileData()
                {
                    Title = "",
                    Count = 0,
                    BackContent = "",
                    BackTitle = "",
                    BackBackgroundImage = new Uri("", UriKind.Relative),
                };

                // Update the default tile
                firstTile.Update(newData);

                RegisterForPushNotifications();
                LoadCurrentUserData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was a problem getting data from the server. Please make sure you are connected to the internet and restart the application");
            }
        }
        private void SetIconsColor()
        {
            var visibility = (Visibility)Application.Current.Resources["PhoneLightThemeVisibility"];
            if (visibility != Visibility.Visible)
            {
                ImageBrush myBrush = new ImageBrush();
                myBrush.ImageSource = new BitmapImage(new Uri("/Resources/Images/panorama_back.png", UriKind.Relative));
                TaskSearchImage.Source = new BitmapImage(new Uri("/Resources/Icons/Dark/appbar.feature.search.rest.png", UriKind.Relative));
                TaskRefreshImage.Source = new BitmapImage(new Uri("/Resources/Icons/Dark/appbar.refresh.rest.png", UriKind.Relative));
                MeLogoutImage.Source = new BitmapImage(new Uri("/Resources/Icons/Dark/appbar.signout.png", UriKind.Relative));
                MeRefreshImage.Source = new BitmapImage(new Uri("/Resources/Icons/Dark/appbar.refresh.rest.png", UriKind.Relative));
                FriendsRefreshImage.Source = new BitmapImage(new Uri("/Resources/Icons/Dark/appbar.refresh.rest.png", UriKind.Relative));
                FriendsSearchImage.Source = new BitmapImage(new Uri("/Resources/Icons/Dark/appbar.feature.search.rest.png", UriKind.Relative));
                ExploreSearchImage.Source = new BitmapImage(new Uri("/Resources/Icons/Dark/appbar.feature.search.rest.png", UriKind.Relative));
                Task2RefreshImage.Source = new BitmapImage(new Uri("/Resources/Icons/Dark/appbar.refresh.rest.png", UriKind.Relative));
                Task2SearchImage.Source = new BitmapImage(new Uri("/Resources/Icons/Dark/appbar.feature.search.rest.png", UriKind.Relative));
                IntroButton.Source = new BitmapImage(new Uri("/Resources/Icons/Dark/appbar.questionmark.rest.png", UriKind.Relative));
                MainPagePanorama.Background = myBrush;
            }
            else
            {
                ImageBrush myBrush = new ImageBrush();
                myBrush.ImageSource = new BitmapImage(new Uri("/Resources/Images/panorama_back_black.png", UriKind.Relative));
                TaskSearchImage.Source = new BitmapImage(new Uri("/Resources/Icons/Light/appbar.feature.search.rest.png", UriKind.Relative));
                TaskRefreshImage.Source = new BitmapImage(new Uri("/Resources/Icons/Light/appbar.refresh.rest.png", UriKind.Relative));
                MeLogoutImage.Source = new BitmapImage(new Uri("/Resources/Icons/Light/appbar.signout.png", UriKind.Relative));
                MeRefreshImage.Source = new BitmapImage(new Uri("/Resources/Icons/Light/appbar.refresh.rest.png", UriKind.Relative));
                FriendsRefreshImage.Source = new BitmapImage(new Uri("/Resources/Icons/Light/appbar.refresh.rest.png", UriKind.Relative));
                FriendsSearchImage.Source = new BitmapImage(new Uri("/Resources/Icons/Light/appbar.feature.search.rest.png", UriKind.Relative));
                ExploreSearchImage.Source = new BitmapImage(new Uri("/Resources/Icons/Light/appbar.feature.search.rest.png", UriKind.Relative));
                Task2RefreshImage.Source = new BitmapImage(new Uri("/Resources/Icons/Light/appbar.refresh.rest.png", UriKind.Relative));
                Task2SearchImage.Source = new BitmapImage(new Uri("/Resources/Icons/Light/appbar.feature.search.rest.png", UriKind.Relative));
                IntroButton.Source = new BitmapImage(new Uri("/Resources/Icons/Light/appbar.questionmark.rest.png", UriKind.Relative));
                MainPagePanorama.Background = myBrush;
            }
        }
        private void GetPanoramaTasks()
        {
            this.panoramaTasks = new List<Task>();
            CivilleDataServiceConnector.AllTasksQuery.BeginExecute(OnTasksQueryComplete, CivilleDataServiceConnector.AllTasksQuery);
        }

        private void OnTasksQueryComplete(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
            {
                DataServiceQuery<Task> query = result.AsyncState as DataServiceQuery<Task>;
                Queue<Task> tasks = new Queue<Task>();
                try
                {
                    foreach (Task task in query.EndExecute(result))
                    {
                        this.panoramaTasks.Add(task);
                        tasks.Enqueue(task);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show("There was a problem getting the data from the server. Please make sure you are connected to the internet");
                }

                foreach (TaskTileControl tileControl in CivilleVisualHelper.FindVisualChildren<TaskTileControl>(this))
                {
                    if (tasks.Count > 0)
                    {
                        Task task = tasks.Dequeue();
                        tileControl.Task = task;
                        tileControl.TitleTextBlock.Text = task.Title;
                        tileControl.TypeTextBlock.Text = task.TaskTypeID == 1 ? "Carbon" : "Diamond";
                        tileControl.ScoreTextBlock.Text = task.Points.ToString();
                        tileControl.Logo.Source = new BitmapImage(new Uri(task.Logo, UriKind.Absolute));
                        tileControl.progressBar.Visibility = Visibility.Collapsed;
                        tileControl.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(TaskTileControl_Tap);
                    }
                    else
                    {
                        tileControl.Visibility = Visibility.Collapsed;
                    }
                }
            });
        }

        private void GetLeaderboardPosition()
        {
            if (UserContext.CurrentUser != null)
            {
                CivilleDataServiceConnector.SetLevelQueryParameters(UserContext.CurrentUser.CurrentLevel);
                CivilleDataServiceConnector.LevelQuery.BeginExecute(OnLevelQueryCompleted, CivilleDataServiceConnector.LevelQuery);
            }

            CivilleDataServiceConnector.SetLeaderboardPositionParameters();
            CivilleDataServiceConnector.LeaderboardPositionQuery.BeginExecute(OnLeaderboardPositionQueryComplete, CivilleDataServiceConnector.LeaderboardPositionQuery);
        }

        private void OnLevelQueryCompleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
            {
                DataServiceQuery<Level> query = result.AsyncState as DataServiceQuery<Level>;
                Level lvl = query.EndExecute(result).First();

                //UserLevelControl.LevelProgressBar.Minimum = 0;
                UserLevelControl.LevelProgressBar.Value = ((UserContext.CurrentUser.Points - UserContext.CurrentUser.LastLevelPoints) / (double)lvl.Points) * 100;
                UserLevelControl.LevelProgressBar2.Value = ((UserContext.CurrentUser.Points - UserContext.CurrentUser.LastLevelPoints) / (double)lvl.Points) * 100;
                UserLevelControl.LevelProgressBar3.Value = ((UserContext.CurrentUser.Points - UserContext.CurrentUser.LastLevelPoints) / (double)lvl.Points) * 100;

                //UserLevelControl.LevelProgressBar.Maximum = lvl.Points;
                UserLevelControl.MaxPointsTextBlock.Text = lvl.Points.ToString();
                UserLevelControl.NrPointsTextBlock.Text = (UserContext.CurrentUser.Points - UserContext.CurrentUser.LastLevelPoints).ToString();
                UserLevelControl.MinPointsTextBlock.Text = "0";
                UserLevelControl.LevelTextBlock.Text = "Level: " + lvl.ID;

                CarbonTasksTxt.Text = "Carbon Tasks - " + UserContext.CurrentUser.CarbonType.ToString() + "/" + lvl.CarbonType.ToString() + " | Diamond Tasks - " + UserContext.CurrentUser.DiamondType.ToString() + "/" + lvl.DiamondType.ToString(); ;
            });
        }

        private void OnLeaderboardPositionQueryComplete(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
            {
                DataServiceQuery<CivilleUser> query = result.AsyncState as DataServiceQuery<CivilleUser>;

                try
                {
                    List<CivilleUser> users = query.EndExecute(result).ToList();

                    //while (UserContext.CurrentUser == null) ;

                    for (int i = 0; i < users.Count(); i++)
                    {
                        CivilleUser user = users.ElementAt(i);
                        if (user.UserName.Equals(UserContext.CurrentUser.UserName))
                        {
                            if (i == 0)
                            {
                                this.FirstLeaderControl.CivilleUser = user;
                                this.FirstLeaderControl.Position = i + 1;
                                this.FirstLeaderControl.LeaderboardBorder.BorderBrush = App.Current.Resources["PhoneAccentBrush"] as SolidColorBrush;
                                this.SecondLeaderControl.CivilleUser = users.ElementAt(i + 1);
                                this.SecondLeaderControl.Position = i + 2;
                                this.SecondLeaderControl.LeaderboardBorder.BorderBrush = null;
                                this.ThirdLeaderControl.CivilleUser = users.ElementAt(i + 2);
                                this.ThirdLeaderControl.Position = i + 3;
                                this.ThirdLeaderControl.LeaderboardBorder.BorderBrush = null;
                                this.SecondLeaderControl.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(FirstLeaderControl_Tap);
                                this.ThirdLeaderControl.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(FirstLeaderControl_Tap);
                            }

                            else if (i == users.Count() - 1)
                            {
                                this.FirstLeaderControl.CivilleUser = users.ElementAt(i - 2);
                                this.FirstLeaderControl.Position = i - 1;
                                this.FirstLeaderControl.LeaderboardBorder.BorderBrush = null;
                                this.SecondLeaderControl.CivilleUser = users.ElementAt(i - 1);
                                this.SecondLeaderControl.Position = i;
                                this.SecondLeaderControl.LeaderboardBorder.BorderBrush = null;
                                this.ThirdLeaderControl.CivilleUser = user;
                                this.ThirdLeaderControl.Position = i + 1;
                                this.ThirdLeaderControl.LeaderboardBorder.BorderBrush = App.Current.Resources["PhoneAccentBrush"] as SolidColorBrush;
                                this.FirstLeaderControl.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(FirstLeaderControl_Tap);
                                this.SecondLeaderControl.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(FirstLeaderControl_Tap);
                            }
                            else
                            {
                                this.FirstLeaderControl.CivilleUser = users.ElementAt(i - 1);
                                this.FirstLeaderControl.Position = i;
                                this.FirstLeaderControl.LeaderboardBorder.BorderBrush = null;
                                this.SecondLeaderControl.CivilleUser = user;
                                this.SecondLeaderControl.Position = i + 1;
                                this.SecondLeaderControl.LeaderboardBorder.BorderBrush = App.Current.Resources["PhoneAccentBrush"] as SolidColorBrush;
                                this.ThirdLeaderControl.CivilleUser = users.ElementAt(i + 1);
                                this.ThirdLeaderControl.Position = i + 2;
                                this.ThirdLeaderControl.LeaderboardBorder.BorderBrush = null;
                                this.FirstLeaderControl.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(FirstLeaderControl_Tap);
                                this.ThirdLeaderControl.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(FirstLeaderControl_Tap);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show("There was a problem getting data from the server");
                }
            });
        }

        private void GetFriends()
        {
            int currentUserID = UserContext.CurrentUser.ID;
            try
            {
                CivilleDataServiceConnector.SetUsersQueryParameters(currentUserID);
                CivilleDataServiceConnector.GetUsersQuery.BeginExecute((result) =>
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        DataServiceQuery<CivilleUser> query = result.AsyncState as DataServiceQuery<CivilleUser>;
                        List<CivilleUser> users = query.EndExecute(result).ToList();

                        //while (UserContext.CurrentUser == null) ;

                        CivilleDataServiceConnector.SetUsersToUsersQueryParameters(currentUserID);
                        CivilleDataServiceConnector.GetUsersToUsersQuery.BeginExecute((result2) =>
                        {
                            Dispatcher.BeginInvoke(() =>
                            {
                                DataServiceQuery<CivilleUserToCivilleUser> query2 = result2.AsyncState as DataServiceQuery<CivilleUserToCivilleUser>;
                                List<CivilleUserToCivilleUser> friends = query2.EndExecute(result2).ToList();
                                int i = 0;
                                foreach (CivilleUserToCivilleUser con in friends)
                                {
                                    CivilleUser friend = users.Where(x => x.ID == con.FriendID).First();
                                    if (i == 6)
                                    {
                                        break;
                                    }
                                    if (i == 0)
                                    {
                                        this.AddFriendButton1.Visibility = Visibility.Collapsed;
                                        this.TileSlider0.Opacity = 1;
                                        this.TileSlider0.Text = friend.FirstName;
                                        this.TileSlider0.LongText = "Level: " + friend.CurrentLevel;
                                        this.TileSlider0.Tag = friend;
                                        this.TileSlider0.InvalidateMeasure();
                                        this.TileSlider0.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(TileSlider5_Tap);
                                        if (friend.Logo != null && !friend.Logo.Equals(""))
                                        {
                                            this.TileSlider0.ImageSource = new BitmapImage(new Uri(friend.Logo, UriKind.Absolute));
                                        }

                                    }
                                    if (i == 1)
                                    {
                                        this.TileSlider1.Opacity = 1;
                                        this.TileSlider1.Text = friend.FirstName;
                                        this.TileSlider1.LongText = "Level: " + friend.CurrentLevel;
                                        this.TileSlider1.Tag = friend;
                                        this.TileSlider1.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(TileSlider5_Tap);
                                        if (friend.Logo != null && !friend.Logo.Equals(""))
                                        {
                                            this.TileSlider1.ImageSource = new BitmapImage(new Uri(friend.Logo, UriKind.Absolute));
                                        }
                                        this.AddFriendButton2.Visibility = Visibility.Collapsed;
                                    }
                                    if (i == 2)
                                    {
                                        this.TileSlider2.Opacity = 1;
                                        this.TileSlider2.Text = friend.FirstName;
                                        this.TileSlider2.LongText = "Level: " + friend.CurrentLevel;
                                        this.TileSlider2.Tag = friend;
                                        this.TileSlider2.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(TileSlider5_Tap);
                                        if (friend.Logo != null && !friend.Logo.Equals(""))
                                        {
                                            this.TileSlider2.ImageSource = new BitmapImage(new Uri(friend.Logo, UriKind.Absolute));
                                        }
                                        this.AddFriendButton3.Visibility = Visibility.Collapsed;
                                    }
                                    if (i == 3)
                                    {
                                        this.TileSlider3.Opacity = 1;
                                        this.TileSlider3.Text = friend.FirstName;
                                        this.TileSlider3.LongText = "Level: " + friend.CurrentLevel;
                                        this.TileSlider3.Tag = friend;
                                        this.TileSlider3.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(TileSlider5_Tap);
                                        if (friend.Logo != null && !friend.Logo.Equals(""))
                                        {
                                            this.TileSlider3.ImageSource = new BitmapImage(new Uri(friend.Logo, UriKind.Absolute));
                                        }
                                        this.AddFriendButton4.Visibility = Visibility.Collapsed;
                                    }
                                    if (i == 4)
                                    {
                                        this.TileSlider4.Opacity = 1;
                                        this.TileSlider4.Text = friend.FirstName;
                                        this.TileSlider4.LongText = "Level: " + friend.CurrentLevel;
                                        this.TileSlider4.Tag = friend;
                                        this.TileSlider4.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(TileSlider5_Tap);
                                        if (friend.Logo != null && !friend.Logo.Equals(""))
                                        {
                                            this.TileSlider4.ImageSource = new BitmapImage(new Uri(friend.Logo, UriKind.Absolute));
                                        }
                                        this.AddFriendButton5.Visibility = Visibility.Collapsed;
                                    }
                                    if (i == 5)
                                    {
                                        this.TileSlider5.Opacity = 1;
                                        this.TileSlider5.Text = friend.FirstName;
                                        this.TileSlider5.LongText = "Level: " + friend.CurrentLevel;
                                        this.TileSlider5.Tag = friend;
                                        this.TileSlider5.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(TileSlider5_Tap);
                                        if (friend.Logo != null && !friend.Logo.Equals(""))
                                        {
                                            this.TileSlider5.ImageSource = new BitmapImage(new Uri(friend.Logo, UriKind.Absolute));
                                        }
                                        this.AddFriendButton6.Visibility = Visibility.Collapsed;
                                    }
                                    i++;
                                }
                                //this.InvalidateMeasure();
                            });
                        }

                        , CivilleDataServiceConnector.GetUsersToUsersQuery);
                    });

                }
                , CivilleDataServiceConnector.GetUsersQuery);
            }
            catch (Exception e)
            {
                MessageBox.Show("There was a problem getting the user data from the server. Please try again.");
            }
        }

        void TileSlider5_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            CivilleUser user = (CivilleUser)(sender as TileSlider).Tag;
            FriendPage.User = user;
            NavigationService.Navigate(new Uri(string.Format("/Views/Pages/FriendPage.xaml"), UriKind.Relative));
        }


        private void BuildExploreTiles()
        {
            ExploreTileControl type1 = new ExploreTileControl();
            type1.Type = 0;
            type1.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(CarbonTasks_Tap);
            type1.SetValue(Grid.RowProperty, 1);
            type1.Margin = new Thickness(10, 0, 10, 10);
            this.ExploreGrid.Children.Add(type1);
            ExploreTileControl type2 = new ExploreTileControl();
            type2.Type = 1;
            type2.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(DiamondTasks_Tap);
            type2.SetValue(Grid.RowProperty, 2);
            type2.Margin = new Thickness(10, 10, 10, 0);
            this.ExploreGrid.Children.Add(type2);

        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Pages/MapPage.xaml", UriKind.Relative));
        }

        private void TileSlider_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Pages/UserProfilePage.xaml", UriKind.Relative));
        }

        private void MeMoreTextBlock_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Pages/ExtrasPivotPage.xaml", UriKind.Relative));
        }

        private void TasksMoreTextBlock_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Pages/TasksPivotPage.xaml?PivotItemId=0", UriKind.Relative));
        }

        private void FriendsMoreTextBlock_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Pages/MyFriendsPage.xaml", UriKind.Relative));
        }

        private void NearMeTextBlock_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Pages/LocalMapPage.xaml", UriKind.Relative));
        }

        private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Pages/SearchTaskResults.xaml?search=" + SearchTextBox.Text, UriKind.Relative));
        }

        private void CarbonTasks_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Pages/TasksPivotPage.xaml?PivotItemId=1", UriKind.Relative));
        }

        private void DiamondTasks_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Pages/TasksPivotPage.xaml?PivotItemId=2", UriKind.Relative));
        }

        private void TaskTileControl_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Task task = (sender as TaskTileControl).Task;
            TaskDetail.Task = task;
            NavigationService.Navigate(new Uri(string.Format("/Views/Pages/TaskDetail.xaml"), UriKind.Relative));
        }

        private void MeTileControl_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Pages/ExtrasPivotPage.xaml", UriKind.Relative));
        }

        private void Refresh_Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            foreach (TaskTileControl tileControl in CivilleVisualHelper.FindVisualChildren<TaskTileControl>(this))
            {
                tileControl.Background = new SolidColorBrush(Colors.Transparent);
                tileControl.progressBar.Visibility = Visibility.Visible;
            }
            GetPanoramaTasks();
        }

        private void AddFriendButton1_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Pages/FriendsMorePage.xaml?friend=", UriKind.Relative));
        }

        private void SearchTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                NavigationService.Navigate(new Uri("/Views/Pages/SearchTaskResults.xaml?search=" + SearchTextBox.Text, UriKind.Relative));
        }

        private void Image_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Pages/SearchTaskResults.xaml?search=" + SearchTextBox.Text, UriKind.Relative));
        }

        private void Image_Tap_2(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Pages/FriendsMorePage.xaml?friend=", UriKind.Relative));
        }

        private void FirstLeaderControl_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            CivilleUser user = (sender as LeaderboardTileControl).CivilleUser;
            FriendPage.User = user;
            NavigationService.Navigate(new Uri("/Views/Pages/FriendPage.xaml", UriKind.Relative));
        }

        private void Task2RefreshImage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            foreach (TaskTileControl tileControl in CivilleVisualHelper.FindVisualChildren<TaskTileControl>(this))
            {
                tileControl.Background = new SolidColorBrush(Colors.Transparent);
                tileControl.progressBar.Visibility = Visibility.Visible;
            }
            GetPanoramaTasks();
        }

        private void Task2SearchImage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Pages/SearchTaskResults.xaml?search=" + SearchTextBox.Text, UriKind.Relative));
        }

        private void MeLogoutImage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            RequestSecurityTokenResponseStore rstrStore = App.Current.Resources["rstrStore"] as RequestSecurityTokenResponseStore;
            rstrStore.RequestSecurityTokenResponse = null;
            NavigationService.Navigate(new Uri("/Views/Pages/SelectAuthPage.xaml", UriKind.Relative));
        }

        private void Start_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Intro.Visibility = Visibility.Collapsed;
        }

        private void Intro_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Intro.Visibility = Visibility.Visible;
        }
    }
}
